package com.java.gulimall.order.interceptor;

import com.java.common.constant.AuthConstant;
import com.java.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jl
 * Created on 2020/9/12
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 远程调用,服务之间的调用无需登录
        // /order/order/getOrderStatus/{orderSn}  /payed/notify
        String requestURI = request.getRequestURI();
        String[] passUrls = new String[]{"/order/order/getOrderStatus/**","/payed/notify"};
        for (String passUrl : passUrls) {
            boolean match = new AntPathMatcher().match(passUrl, requestURI);
            if (match) {
                return true;
            }
        }
        MemberResponseVo memberResponseVo = (MemberResponseVo) request.getSession().getAttribute(AuthConstant.LOGIN_USER);
        if (memberResponseVo != null) {
            loginUser.set(memberResponseVo);
            return true;
        } else {
            // 重定向到登录页面
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
